<template>
  <!-- 访问地域分布 -->
  <div class="component-access-area">
    <title-bar
      :title="$t('dataAnalysis.visitsGeo')"
      :tips-content="$t('dataAnalysis.userRegion')"
      :show-export="isAuth('user:analysis:data:export')"
      @export="exportCategory"
    />
    <div class="chart">
      <div
        id="region-echart-left"
        class="chart-left"
        style="width: 100%; height: 400px"
      />
      <div
        id="region-echart-right"
        class="chart-right"
        style="width: 100%; height: 410px;"
      />
    </div>
    <div class="table">
      <el-table
        :data="props.tableData"
        :header-cell-style="{
          background:'#f9f9f9',
          height:'50px'
        }"
        :row-style="{height:'50px'}"
        stripe
      >
        <el-table-column
          prop="amount1"
          :label="$t('brand.serialNumber')"
          width="120"
        />
        <el-table-column
          prop="amount2"
          :label="$t('dataAnalysis.area')"
          width="180"
        />
        <el-table-column
          prop="amount3"
          sortable
          :label="$t('dataAnalysis.pageviews')"
        />
        <el-table-column
          prop="amount4"
          :label="$t('dataAnalysis.numberOfVisitors')"
        />
        <el-table-column
          prop="amount5"
          :label="$t('dataAnalysis.productViews')"
        />
        <el-table-column
          prop="amount6"
          :label="$t('dataAnalysis.geoContent')"
        />
      </el-table>
    </div>
  </div>
</template>

<script setup>
import titleBar from './title-bar.vue'
import * as $echarts from 'echarts'
import { ElLoading, ElMessage } from 'element-plus'
import { isAuth } from '@/utils'
import { chinaMap } from '../js/chinaJson.js'

const props = defineProps({
  dateType: {
    type: Number,
    default: 1
  },
  dateRange: {
    type: Array,
    default: () => ([])
  },
  tableData: {
    type: Array,
    default: () => ([])
  },
  regionData: {
    type: Object,
    default: () => ({
      xData: [],
      seriesData: []
    })
  }
})

watch(() => props.regionData, () => {
  getRegionEchartLeft()
  getRegionEchartRight()
}, { deep: true })

// 导出
const exportCategory = Debounce(() => {
  const loading = ElLoading.service({
    lock: true,
    target: '.region',
    customClass: 'export-load',
    background: 'transparent',
    text: $t('shop.exportIng')
  })
  http({
    url: http.adornUrl('/platform/flowUserAnalysis/userAnalysisDataExport'),
    method: 'get',
    params: http.adornParams({
      type: props.dateType,
      start: props.dateRange[0] || null,
      end: props.dateRange[1] || null
    }),
    responseType: 'blob'
  }).then(({ data }) => {
    loading.close()
    const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' })
    const fileName = $t('dataAnalysis.visitsGeo') + '.xlsx'
    const elink = document.createElement('a')
    if ('download' in elink) {
      elink.download = fileName
      elink.style.display = 'none'
      elink.href = URL.createObjectURL(blob)
      document.body.appendChild(elink)
      elink.click()
      // URL.revokeObjectURL(elink.href) // 释放URL 对象
      // document.body.removeChild(elink)
    } else {
      navigator.msSaveBlob(blob, fileName)
    }
    ElMessage({
      message: $t('shop.exportSuccess'),
      type: 'success',
      duration: 1500
    })
  }).catch(() => {
    loading.close()
  })
})

// 获取访问地域分布左边边的数据图

let oldDataList = []
const onMapsDate = () => {
  const tempOldDataList = [
    { name: '南海诸岛', label: $t('dataAnalysis.southIslands'), value: 0 },
    { name: '北京市', label: $t('dataAnalysis.bj'), value: 0 },
    { name: '天津市', label: $t('dataAnalysis.tj'), value: 0 },
    { name: '上海市', label: $t('dataAnalysis.sh'), value: 0 },
    { name: '重庆市', label: $t('dataAnalysis.cq'), value: 0 },
    { name: '河北省', label: $t('dataAnalysis.hb'), value: 0 },
    { name: '河南省', label: $t('dataAnalysis.hn'), value: 0 },
    { name: '云南省', label: $t('dataAnalysis.yn'), value: 0 },
    { name: '辽宁省', label: $t('dataAnalysis.ln'), value: 0 },
    { name: '黑龙江省', label: $t('dataAnalysis.hlj'), value: 0 },
    { name: '湖南省', label: $t('dataAnalysis.hunan'), value: 0 },
    { name: '安徽省', label: $t('dataAnalysis.ah'), value: 0 },
    { name: '山东省', label: $t('dataAnalysis.sd'), value: 0 },
    { name: '新疆维吾尔自治区', label: $t('dataAnalysis.xj'), value: 0 },
    { name: '江苏省', label: $t('dataAnalysis.js'), value: 0 },
    { name: '浙江省', label: $t('dataAnalysis.zj'), value: 0 },
    { name: '江西省', label: $t('dataAnalysis.jx'), value: 0 },
    { name: '湖北省', label: $t('dataAnalysis.hubei'), value: 0 },
    { name: '广西壮族自治区', label: $t('dataAnalysis.gx'), value: 0 },
    { name: '甘肃省', label: $t('dataAnalysis.gs'), value: 0 },
    { name: '山西省', label: $t('dataAnalysis.sx'), value: 0 },
    { name: '内蒙古自治区', label: $t('dataAnalysis.nm'), value: 0 },
    { name: '陕西省', label: $t('dataAnalysis.shanxi'), value: 0 },
    { name: '吉林省', label: $t('dataAnalysis.jl'), value: 0 },
    { name: '福建省', label: $t('dataAnalysis.fj'), value: 0 },
    { name: '贵州省', label: $t('dataAnalysis.gz'), value: 0 },
    { name: '广东省', label: $t('dataAnalysis.gd'), value: 0 },
    { name: '青海省', label: $t('dataAnalysis.qh'), value: 0 },
    { name: '西藏自治区', label: $t('dataAnalysis.xz'), value: 0 },
    { name: '四川省', label: $t('dataAnalysis.sc'), value: 0 },
    { name: '宁夏回族自治区', label: $t('dataAnalysis.nx'), value: 0 },
    { name: '海南省', label: $t('dataAnalysis.hainan'), value: 0 },
    { name: '台湾省', label: $t('dataAnalysis.tw'), value: 0 },
    { name: '香港', label: $t('dataAnalysis.hk'), value: 0 },
    { name: '澳门', label: $t('dataAnalysis.macau'), value: 0 }
  ]
  const newDataList = props.regionData.seriesData
  // 循环赋值，有数据的更新
  for (let i = 0; i < newDataList.length; i++) {
    for (let j = 0; j < tempOldDataList.length; j++) {
      if (newDataList[i].name === tempOldDataList[j].name) {
        tempOldDataList[j].value = newDataList[i].value
      }
    }
  }
  oldDataList = tempOldDataList
}
const getRegionEchartLeft = () => {
  onMapsDate()
  $echarts.registerMap('china', chinaMap)
  // 有的话就获取已有echarts实例的DOM节点
  let myChart = $echarts.getInstanceByDom(document.getElementById('region-echart-left'))
  // 如果不存在，就进行初始化
  if (myChart == null) {
    myChart = $echarts.init(document.getElementById('region-echart-left'))
  }
  const option = {
    tooltip: {
      formatter: function (params) {
        return params.seriesName + '<br />' + params.name + '：' + params.value
      } // 数据格式化
    },
    visualMap: {
      min: 0,
      left: 'left',
      top: 'bottom',
      itemHeight: 100,
      text: [$t('dataAnalysis.height'), $t('dataAnalysis.low')], // 取值范围的文字
      inRange: {
        color: ['#e2e2e2', '#0595d4'] // 取值范围的颜色
      },
      show: true // 图注
    },
    geo: {
      map: 'china',
      roam: false, // 不开启缩放和平移
      zoom: 1.23, // 视角缩放比例
      label: {
        show: true,
        fontSize: '10',
        color: 'rgba(0,0,0,0.7)'
      },
      emphasis: {
        areaColor: '#258ffa', // 鼠标选择区域颜色
        shadowOffsetX: 0,
        shadowOffsetY: 0,
        shadowBlur: 20,
        borderWidth: 0,
        shadowColor: 'rgba(0, 0, 0, 0.5)',
        itemStyle: {
          borderColor: 'rgba(0, 0, 0, 0.2)'
        }
      }
    },
    series: [
      {
        name: $t('dataAnalysis.pageviews'),
        type: 'map',
        map: 'china',
        geoIndex: 0,
        label: {
          show: true
        },
        data: oldDataList
      }
    ]
  }
  myChart.setOption(option)
  window.addEventListener('resize', function () {
    myChart.resize()
  })
}

// 获取访问地域分布右边的数据图
const getRegionEchartRight = () => {
  const randomColor = []
  for (let i = 1; i <= 34; i++) {
    let z = 0
    let str = '#'
    let random = 0
    const aryNum = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F']
    for (z = 0; z < 6; z++) {
      random = parseInt(Math.random() * 16)

      str += aryNum[random]
    }
    randomColor.push(str)
  }
  let myChart = $echarts.getInstanceByDom(document.getElementById('region-echart-right'))
  // 如果不存在，就进行初始化
  if (myChart == null) {
    myChart = $echarts.init(document.getElementById('region-echart-right'))
  }
  const option = {
    title: {
      text: $t('dataAnalysis.pageviews'),
      left: 'center',
      textStyle: {
        color: '#666',
        fontWeight: '500',
        fontSize: 12
      }
    },
    color: randomColor,
    tooltip: {
      trigger: 'item',
      formatter: `{b} <br/>{a}: {c} <br/>${$t('home.Percentage')}:{d}%`
    },
    legend: {
      orient: 'vertical',
      top: 20,
      right: 'left',
      data: props.regionData.xData
    },
    series: [
      {
        name: $t('dataAnalysis.pageviews'),
        type: 'pie',
        radius: ['72%', '28%'],
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '14',
            color: '#888'
          }
        },
        labelLine: {
          show: false
        },
        data: props.regionData.seriesData
      }
    ]
  }
  myChart.setOption(option)
  window.addEventListener('resize', function () {
    myChart.resize()
  })
  setTimeout(() => {
    myChart.resize()
  }, 300)
}

</script>

<style lang="scss" scoped>
.component-access-area {
  .chart {
    display: flex;
    .chart-left {
      width: 35%;
    }
    .chart-right {
      width: 65%;
      padding: 0 0 20px;
    }
  }
}
</style>
